package br.com.manutencao.repositories;

import java.io.Serializable;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

public class Repository<T> implements Serializable {

	
	private static final long serialVersionUID = 1L;

	
	private Class<T> entidade;
	
	private EntityManager em = Persistence.createEntityManagerFactory("jsf")
			.createEntityManager();

	public Repository(Class<T> entity) {
		entidade = entity;
	}

	public T buscaPorId(Integer id) {
		return em.find(entidade, id);
	}

	@SuppressWarnings("unchecked")
	public Collection<T> buscaTodos() {
		return em.createQuery("from " + entidade.getName()).getResultList();
	}

	public void adiciona(T t) {
		em.getTransaction().begin();
		em.persist(t);
		em.getTransaction().commit();
	}

	public void delete(T t) {
		em.getTransaction().begin();
		em.remove(t);
		em.getTransaction().commit();
	}
	
	public void altera(T t){
		em.getTransaction().begin();
		em.merge(t);
		em.getTransaction().commit();
	}
}
